package ink.feny.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * TODO
 * @author Feny
 * @date Created in 2021/4/28
 */
@Component
public class UserAuthProvider implements AuthenticationProvider {
    @Autowired
    private UserAuthService authService;

    /**
     * 认证处理
     * @param authentication 认证请求信息
     * @return 返回认证结果
     * @author Feny
     * @date 2021/4/26
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        // 查询用户信息
        UserDetails userDetails = authService.loadUserByUsername(username);
        if (null == userDetails) {
            throw new BadCredentialsException("认证失败");
        }

        return new UsernamePasswordAuthenticationToken(username, password);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UserAuthProvider.class.isAssignableFrom(aClass);
    }
}
